package com.serkol.ams.controller.api;

import cn.hutool.core.codec.Base62;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.serkol.ams.bean.ImageInfoRect;
import com.serkol.ams.bean.MyPageOld;
import com.serkol.ams.bean.Result;
import com.serkol.ams.entity.LoginLog;
import com.serkol.ams.entity.Poster;
import com.serkol.ams.entity.PosterDevise;
import com.serkol.ams.entity.PosterImage;
import com.serkol.ams.service.*;
import com.serkol.annotation.IsLogin;
import com.serkol.constant.AuthConstant;
import com.serkol.constant.ResultConstant;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/poster")
public class PosterApiController {
    @Value("${upload.host}")
    private String uploadhost;
    @Autowired
    private PosterService posterService;

    @Autowired
    private PosterDeviseService deviseService;
    @Autowired
    private PosterImageService imageService;

    @Autowired
    private UsersAuthenticationService authenticationService;
    @Autowired
    private UsersService usersService;

    @Autowired
    private PicturesService picturesService;
    @Value("${upload.path}")
    private String uploadpath;

    @IsLogin
    @GetMapping("/findByPageList")
    public Result findByPageList(@RequestParam(name = "pageSize", defaultValue = "10") int pageSize, @RequestParam(name = "current", defaultValue = "0") int current) {
        AuthConstant.setPathUrl(uploadhost);
        Result result = new Result();
       return posterService.findByList(pageSize, current);

    }

    @IsLogin
    @GetMapping("/findByDataList")
    public Result findByDataList() {
        AuthConstant.setPathUrl(uploadhost);
        Result result = new Result();
        List<Map<String, Object>> list = posterService.findByDataList();
        if (list.size() > 0) {
            result.setStatus(ResultConstant.SUCSESS);
            result.setData(list);
        } else {
            result.setStatus(ResultConstant.EMPTIY);
        }
        return result;
    }


    @GetMapping("/findByDataMiniTypeList")
    public Result findByDataMiniTypeList(@RequestParam(name = "type", required = true) int type) {
        AuthConstant.setPathUrl(uploadhost);
        Result result = new Result();
        List<Map<String, Object>> list = imageService.findByDataMiniTypeList(type);
        if (list.size() > 0) {
            result.setStatus(ResultConstant.SUCSESS);
            result.setData(list);
        } else {
            result.setStatus(ResultConstant.EMPTIY);
        }
        return result;
    }

    //video
    @IsLogin
    @PostMapping("edit")
    public Result edit(@RequestBody Poster sysCategory) {

        boolean b = false;
        if (sysCategory.getId() != null && sysCategory.getId() > 0) {
            b = posterService.updateById(sysCategory);
        } else {
            b = posterService.save(sysCategory);
        }
        return b ? Result.ok() : Result.failure(ResultConstant.FAIL);
    }

    @IsLogin
    @PostMapping("editKeys")
    public Result editKeys(@RequestBody JSONObject object) {
        long id = object.getLongValue("id");
        String attrs = object.getString("attrs");
        System.out.println(attrs);
        boolean b = false;
        if (id > 0) {
            Poster poster = new Poster();
            poster.setId(id);
            poster.setAttr(attrs);
            b = posterService.updateById(poster);
        }
        return b ? Result.ok() : Result.failure(ResultConstant.FAIL);
    }


    @IsLogin
    @PostMapping("posterEdit")
    public Result posterEdit(@RequestBody JSONObject object) {
        System.out.println(object);
        boolean b = false;
        JSONObject data = object.getJSONObject("data");
        PosterImage posterImage = data.toJavaObject(PosterImage.class);
        JSONArray posters = object.getJSONArray("posters");
        List<PosterDevise> posterDevises = posters.toJavaList(PosterDevise.class);
        b = imageService.save(posterImage);
        if (b) {
            List<PosterDevise> posterDevisesS = new ArrayList<>();
            Iterator<PosterDevise> iterator = posterDevises.iterator();
            while (iterator.hasNext()) {
                PosterDevise next = iterator.next();
                next.setPosterId(posterImage.getId());

                posterDevisesS.add(next);
            }
            deviseService.saveBatch(posterDevisesS);
        }
        //   List<PosterDevise> posterDevises = array.toJavaList(PosterDevise.class);
        //   System.out.println(posterDevises);
        return b ? Result.ok() : Result.failure(ResultConstant.FAIL);
    }


    @IsLogin
    @GetMapping("/findByDataImageList")
    public Result findByDataImageList(@RequestParam(name = "id", defaultValue = "0") long id) {
        AuthConstant.setPathUrl(uploadhost);

        Result result = new Result();
        List<Map<String, Object>> list = imageService.findByDataList(id);
        if (list.size() > 0) {
            result.setStatus(ResultConstant.SUCSESS);
            result.setData(list);
        } else {
            result.setStatus(ResultConstant.EMPTIY);
        }
        return result;
    }

    @IsLogin
    @GetMapping(value = "/image")
    public Result image(@RequestParam(name = "id", defaultValue = "0") long id,
                        @RequestParam(name = "type", defaultValue = "0") int type,
                        @RequestParam(name = "page", defaultValue = "pages/index/index") String current) throws IOException, WxErrorException, URISyntaxException, FontFormatException {
        AuthConstant.setPathUrl("");
        LoginLog loginLog = AuthConstant.getLoginLog();
        System.out.println(loginLog);
        //  String page = "pages/index/index";
        //  int type = 2;
        String pages = current + "?type=" + type + "&userId=" + loginLog.getUserId() + "goodsId=" + id;
        String key = Base62.encode(pages);
        String base64 = posterService.createImage(current, type, loginLog.getUserId(), pages, key, id);

        return Result.ok(base64);
    }

    @IsLogin
    @GetMapping(value = "/imagePoster")
    public Result imagePoster(@RequestParam(name = "id", defaultValue = "0") long id,
                        @RequestParam(name = "type", defaultValue = "0") int type,
                        @RequestParam(name = "page", defaultValue = "pages/index/index") String current) throws IOException, WxErrorException, URISyntaxException, FontFormatException {
        AuthConstant.setPathUrl("");
        LoginLog loginLog = AuthConstant.getLoginLog();
        System.out.println(loginLog);
        //  String page = "pages/index/index";
        //  int type = 2;
        String pages = current + "?type=" + type + "&userId=" + loginLog.getUserId() + "&posterId=" + id;

        String base64 = posterService.createImage(loginLog.getUserId(), pages, id);

        return Result.ok(base64);
    }

    @IsLogin
    @GetMapping(value = "/imagePosterData")
    public Result imagePosterData(@RequestParam(name = "id", defaultValue = "0") long id,
                              @RequestParam(name = "type", defaultValue = "0") int type,
                              @RequestParam(name = "page", defaultValue = "pages/index/index") String current) throws IOException, WxErrorException, URISyntaxException, FontFormatException {
        AuthConstant.setPathUrl("");
        LoginLog loginLog = AuthConstant.getLoginLog();
        System.out.println(loginLog);
        //  String page = "pages/index/index";
        //  int type = 2;
        String pages = current + "?type=" + type + "&userId=" + loginLog.getUserId() + "&posterId=" + id;

        String base64 = posterService.createImage(loginLog.getUserId(), pages, id);

        return Result.ok(base64);
    }
    @IsLogin
    @PostMapping(value = "/byDeleteImage")
    public Result byDeleteImage(@RequestBody JSONObject object) {
        long id = object.getLongValue("id");
        AuthConstant.setPathUrl("");
        LoginLog loginLog = AuthConstant.getLoginLog();
        int i = imageService.getBaseMapper().deleteById(id);
        if (i > 0) {
            QueryWrapper<PosterDevise> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(PosterDevise::getPosterId, id);
            deviseService.getBaseMapper().delete(queryWrapper);
        }
        return (i > 0) ? Result.ok() : Result.failure();
    }

    @IsLogin
    @GetMapping(value = "/myQrcode")
    public Result myQrcode(
            @RequestParam(name = "type", defaultValue = "0") int type) throws IOException, WxErrorException, URISyntaxException, FontFormatException {
        AuthConstant.setPathUrl("");
        LoginLog loginLog = AuthConstant.getLoginLog();
        //  String page = "pages/index/index";
        //  int type = 2;
     //   String pages = page + "?type=" + type + "&userId=" + loginLog.getUserId() + "goodsId=" + id;
     //   String key = Base62.encode(pages);
        String base64 = posterService.myQrcode(type, loginLog.getUserId());

     //   BufferedImage bufferedImage = ImageBase64Util.base64ToBufferedImage(base64);
      //  ByteArrayOutputStream out = new ByteArrayOutputStream();
        //ImageIO.write(bufferedImage, "png", out);
        return Result.ok(base64);
    }

    //@IsLogin
    @GetMapping(value = "/regesterQrcode")
    public Result regesterQrcode(
            @RequestParam(name = "userId", defaultValue = "0") long userId) throws IOException, WxErrorException, URISyntaxException, FontFormatException {
        AuthConstant.setPathUrl("");
        LoginLog loginLog = AuthConstant.getLoginLog();
        //  String page = "pages/index/index";
        //  int type = 2;
        //   String pages = page + "?type=" + type + "&userId=" + loginLog.getUserId() + "goodsId=" + id;
        //   String key = Base62.encode(pages);
        String base64 = posterService.regesterQrcode(userId);

        //   BufferedImage bufferedImage = ImageBase64Util.base64ToBufferedImage(base64);
        //  ByteArrayOutputStream out = new ByteArrayOutputStream();
        //ImageIO.write(bufferedImage, "png", out);
        return Result.ok("data:image/png;base64,"+base64);
    }


    @IsLogin
    @GetMapping(value = "/sharePoster")
    public Result sharePoster(@RequestParam(name = "id", defaultValue = "0") long id,
                              @RequestParam(name = "type", defaultValue = "0") int type,
                              @RequestParam(name = "page", defaultValue = "pages/index/index") String current) throws WxErrorException, IOException {
        AuthConstant.setPathUrl(uploadhost);
        LoginLog loginLog = AuthConstant.getLoginLog();
        System.out.println(loginLog);
        //  String page = "pages/index/index";
        //  int type = 2;
        String pages = current + "?type=0&userId=" + loginLog.getUserId() + "&posterId=" + id;

        Map<String,Object> base64 = posterService.sharePoster(loginLog.getUserId(), pages, id);
        System.out.println(base64);
        return Result.ok(base64);
    }

    @IsLogin
    @GetMapping(value = "/sharePosterData")
    public Result sharePosterData(@RequestParam(name = "id", defaultValue = "0") long id,
                                  @RequestParam(name = "type", defaultValue = "0") int type,
                                  @RequestParam(name = "page", defaultValue = "pages/index/index") String current) throws IOException, WxErrorException, URISyntaxException, FontFormatException {
        AuthConstant.setPathUrl(uploadhost);
        LoginLog loginLog = AuthConstant.getLoginLog();
        System.out.println(loginLog);
        //  String page = "pages/index/index";
        //  int type = 2;
        String pages = current + "?type=" + type + "&userId=" + loginLog.getUserId() + "&posterId=" + id;

        Map<String,Object> base64 = posterService.sharePosterRand(loginLog.getUserId(), pages, type,id);

        return Result.ok(base64);
    }
}
